package com.android.exchangeapp

import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowInsetsControllerCompat
import com.android.exchangeapp.databinding.WebviewActivityBinding

/**
 * Created by Matt on 2023/9/10.
 **/
class WebPageActivity : AppCompatActivity() {
    companion object {
        private const val FILE_CHOOSER_RESULT_CODE = 0x01
        private const val TAG = "WebPageActivity"
        fun start(context: Context, url: String) {
            context.startActivity(Intent(context, WebPageActivity::class.java).putExtra("url", url))
        }
    }

    private lateinit var mBinding: WebviewActivityBinding

    var mWebClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
        }

        override fun onLoadResource(view: WebView?, url: String?) {
            if (!PageManager.onLoadResource(this@WebPageActivity, view, url)) {
                super.onLoadResource(view, url)
            }
        }

        override fun shouldOverrideUrlLoading(
            webView: WebView,
            url: String
        ): Boolean {     //检测某第三方关键词的时候跳出浏览器
            return try {
                Log.e("Matt", "url: $url")
                val uri = Uri.parse(url) //老版本
                PageManager.handleUri(this@WebPageActivity, uri, webView)
            } catch (e: Exception) {
                false
            }
        }

        @TargetApi(Build.VERSION_CODES.N)
        override fun shouldOverrideUrlLoading(
            view: WebView,
            request: WebResourceRequest
        ): Boolean {//检测某第三方关键词的时候跳出浏览器
            return try {
                Log.e("Matt", "url: ${request.url}")
                val uri = request.url //新版本
                PageManager.handleUri(this@WebPageActivity, uri, view)
            } catch (e: Exception) {
                false
            }
        }

        override fun onReceivedSslError(
            webView: WebView?,
            sslErrorHandler: SslErrorHandler,
            sslError: SslError?,
        ) {
            sslErrorHandler.cancel();   //终端运行
        }
    }
    var mWebChromeClient = object : WebChromeClient() {
        override fun onShowFileChooser(
            webView: WebView?,
            filePathCallback: ValueCallback<Array<Uri?>?>,
            fileChooserParams: FileChooserParams?,
        ): Boolean {
            uploadMessageAboveL = filePathCallback
            openImageChooserActivity()
            return true
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {  //进度条显示
            super.onProgressChanged(view, newProgress)
            if (newProgress == 100) {
                mBinding.progressBar.visibility = View.GONE
            } else {
                mBinding.progressBar.visibility = View.VISIBLE
                mBinding.progressBar.progress = newProgress
            }
        }

        override fun onCreateWindow(
            view: WebView,
            isDialog: Boolean,
            isUserGesture: Boolean,
            resultMsg: Message,
        ): Boolean {
            val newWebView = WebView(view.context)
            newWebView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    startActivity(
                        Intent(this@WebPageActivity, SecondWebPageActivity::class.java)
                            .putExtra("url", url)
                    )
                    return true
                }
            }
            val transport = resultMsg.obj as WebView.WebViewTransport
            transport.webView = newWebView
            resultMsg.sendToTarget()
            return true
        }

        override fun onCloseWindow(window: WebView?) {
            super.onCloseWindow(window)
        }

    }

    private var uploadMessageAboveL: ValueCallback<Array<Uri?>?>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.webview_activity)
        PageManager.jumpInfo?.let {
            applyStatusBar(it)
        }
        mBinding = WebviewActivityBinding.bind(findViewById(R.id.root)).apply {
            webview.settings.applySettings()
            webview.setInitialScale(100)
            webview.webViewClient = mWebClient
            webview.webChromeClient = mWebChromeClient
            webview.loadUrl(intent.getStringExtra("url") ?: "")
        }
    }

    override fun onResume() {
        super.onResume()
        mBinding.webview.onResume()
    }

    private fun WebSettings.applySettings() {
        javaScriptEnabled = true
        cacheMode = WebSettings.LOAD_NO_CACHE
        setSupportZoom(true)
        builtInZoomControls = true
        displayZoomControls = false
        useWideViewPort = true
        loadWithOverviewMode = true
        builtInZoomControls = true
        allowFileAccess = true
        domStorageEnabled = true
        databaseEnabled = true
        setSupportMultipleWindows(true) // 支持多窗口
        javaScriptCanOpenWindowsAutomatically = true
    }

    private fun openImageChooserActivity() {
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*"
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE)
    }

    private fun setStatusBarColor(color: Int, colorIsLight: Boolean) {
        val windowController = WindowInsetsControllerCompat(window, window.decorView)
        windowController.isAppearanceLightStatusBars = colorIsLight
        window.statusBarColor = color
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(data)
            }
        }
    }

    private fun onActivityResultAboveL(intent: Intent?) {
        if (uploadMessageAboveL == null) return
        var results: Array<Uri?>? = null
        if (intent != null) {
            val dataString = intent.dataString
            val clipData = intent.clipData
            if (clipData != null) {
                results = arrayOfNulls(clipData.itemCount)
                for (i in 0 until clipData.itemCount) {
                    val item = clipData.getItemAt(i)
                    results[i] = item.uri
                }
            }
            if (dataString != null) results = arrayOf(Uri.parse(dataString))
        }
        uploadMessageAboveL?.onReceiveValue(results)
        uploadMessageAboveL = null
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode != KeyEvent.KEYCODE_BACK) {
            return super.onKeyDown(keyCode, event)
        }
        if (mBinding.webview.canGoBack()) {
            mBinding.webview.goBack() //goBack()表示返回WebView的上一页面
            return true
        } else {
            mBinding.webview.stopLoading()
            mBinding.webview.destroy()
            finish()
        }
        return false
    }
}